<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryParams" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主题" prop="cmTitle">
        <el-input v-model="queryParams.cmTitle" placeholder="请输入班会主题" clearable />
      </el-form-item>
      <el-form-item label="内容" prop="cmTheme">
        <el-input v-model="queryParams.cmTheme" placeholder="请输入班会主题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="开始时间" prop="cmStart">
        <el-date-picker clearable v-model="queryParams.cmStart" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择计划开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="cmEnd">
        <el-date-picker clearable v-model="queryParams.cmEnd" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择班会计划结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ClassMettingThemeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="${comment}" align="center" prop="cmId" v-if="false" />
      <el-table-column label="编码" align="center" prop="cmId" width="60px" />
      <el-table-column label="班会标题" align="center" prop="cmTitle" :show-overflow-tooltip="true" />
      <el-table-column label="主题内容" align="center" prop="cmTextTheme" :show-overflow-tooltip="true" />
      <el-table-column label="是否需要上传材料" align="center" prop="cmIsupload">
        <template slot-scope="scope">
          {{ scope.row.cmIsupload == 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="班会分类" align="center" prop="cmProp">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.rt_cm_type" :value="scope.row.cmProp" />
        </template>
      </el-table-column>
      <el-table-column label="班会计划开始时间" align="center" prop="cmStart" width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cmStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班会计划结束时间" align="center" prop="cmEnd" width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cmEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :formatter="getStatusName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180px" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding" width="160px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="lookVClick(scope.row)">查看提交情况</el-button>
          <el-button v-if="scope.row.status == 0" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleOpenDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改班会主题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">

        <el-form-item label="班会标题" prop="cmTitle">
          <el-input v-model="form.cmTitle" placeholder="请输入班会标题" />
        </el-form-item>
        <el-form-item label="主题内容" prop="cmTheme">
          <!-- <el-input v-model="form.cmTheme" type="textarea" placeholder="请输入内容" /> -->
          <editor v-model="form.cmTheme" ref="uedit" :min-height="192" />
        </el-form-item>
        <el-form-item label="是否需要上传材料" prop="cmIsupload">
          <el-select v-model="form.cmIsupload" placeholder="请选择否需要上传材料">
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班会分类" prop="cmProp">
          <el-select v-model="form.cmProp" placeholder="请选择班会性质">
            <el-option v-for="dict in dict.type.rt_cm_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="班会计划开始时间" prop="cmStart">
          <el-date-picker clearable v-model="form.cmStart" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择班会计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="班会计划结束时间" prop="cmEnd">
          <el-date-picker clearable v-model="form.cmEnd" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择班会计划结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="附件上传">
          <AttachUpload :fileListPut="tmpResList" v-model="form.attachUrls"></AttachUpload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm(0)">保 存</el-button> -->
        <el-button type="primary" @click="submitForm(1)">发 布</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="detailOpen" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="班会标题" prop="cmTitle">
          <el-input v-model="form.cmTitle" placeholder="请输入班会标题" disabled />
        </el-form-item>
        <el-form-item label="主题内容" prop="cmTheme">
          <div v-html="form.cmTheme"></div>
        </el-form-item>
        <el-form-item label="是否需要上传材料" prop="cmIsupload" disabled>
          <el-select v-model="form.cmIsupload" placeholder="请选择否需要上传材料" disabled>
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班会分类" prop="cmProp" disabled>
          <el-select v-model="form.cmProp" placeholder="" disabled>
            <el-option v-for="dict in dict.type.rt_cm_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="班会计划开始时间" prop="cmStart">
          <el-date-picker clearable disabled v-model="form.cmStart" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择班会计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="班会计划结束时间" prop="cmEnd">
          <el-date-picker clearable disabled v-model="form.cmEnd" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择班会计划结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="附件">
          <AttachUpload :fileListPut="tmpResList" :isShowBtn="false" :isShowTip="false"></AttachUpload>
        </el-form-item>
        <el-form-item label="备注" prop="remark" disabled>
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="提交情况" :visible.sync="lookV" width="1200px" append-to-body>
      <el-input clearable style="width:400px" placeholder="输入关键字进行过滤" v-model="filterText" />
      <el-button style="margin-left:10px;" type="primary" @click="lookSubmit('未提交')">只查看未提交</el-button>
      <el-button style="margin-left:10px;" type="success" @click="lookSubmit('已提交')">只查看已提交</el-button>
      <el-button style="margin-left:10px;" type="success" @click="lookSubmit('')">查看所有</el-button>
      <el-tree :data="lookTreeData" v-if="lookV" :render-content="renderContent" ref="tree" :props="props"
        :filter-node-method="filterNode" default-expand-all>
      </el-tree>
    </el-dialog>


  </div>
</template>

<script>
import { listTreeDept, listClassByMajorId, listMajorsByDeptId, listDept, listClassMettingTheme, getClassMettingTheme, delClassMettingTheme, addClassMettingTheme, updateClassMettingTheme } from "@/api/routine/theme/ClassMettingTheme";
import AttachUpload from "@/components/AttachUpload"
import { isEmpty, fullLoading } from "@/api/helpFunc";

export default {
  name: "ClassMettingTheme",
  dicts: ['rt_cm_type'],
  components: { AttachUpload },
  data() {
    return {

      filterText: '',

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班会主题表格数据
      ClassMettingThemeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //获取纯文本
      themestr: "",
      //附件列表
      tmpResList: [],
      //详情弹出层
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cmNo: null,
        cmTheme: null,
        cmTitle: null,
        cmIsupload: null,
        cmProp: null,
        cmStart: null,
        cmEnd: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      lookV: false,

      props: {
        label: 'label',
        children: 'children',
        isLeaf: 'leaf'
      },

      lookCmNo: null,
      lookTreeData: []

    };
  },
  created() {
    this.getList();
    //this.listDept();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    lookSubmit(val) {
      this.$refs.tree.filter(val);
    },
    renderContent(h, { node, data, store }) {
      if (node.level == 3) {
        if (data.label.includes("未提交")) {
          return h('span', {
            style: {
              color: "red"
            }
          }, data.label);
        } else {
          return h('span', {
            style: {
              color: "green"
            }
          }, data.label);
        }

      } else {
        return h('span', {
          style: {
            color: "black"
          }
        }, data.label);
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    async listTreeDept() {
      let loading = fullLoading(this);
      let res = await listTreeDept(this.lookCmNo);
      loading.close();
      if (res.code == 200) {
        let data = [...res.data];
        this.lookTreeData = data;
      }
    },

    async listDept() {
      this.lookList = [];
      let loading = fullLoading(this);
      let res = await listDept();
      loading.close();
      if (res.code == 200) {
        let data = [...res.data];
        data.map(x => {
          x.label = x.deptName;
          x.name = x.deptName
          x.value = x.deptId;
          x.isLeaf = "leaf";
          x.id = x.deptId;
          this.lookList.push(x);
        });
      }

    },
    async loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([...this.lookList]);
      }
      let id = node.data.id;
      if (node.level == 1) {
        let loading = fullLoading(this);
        let res = await listMajorsByDeptId(id);
        loading.close();
        if (res.code == 200) {
          let data = [...res.data];
          data.map(x => {
            x.id = x.majorId;
            x.label = x.majorName;
            x.name = x.majorName;
          });
          resolve(data);
        } else {
          resolve([]);
        }
      }

      if (node.level == 2) {
        let loading = fullLoading(this);
        let res = await listClassByMajorId(id, this.lookCmNo);
        loading.close();
        if (res.code == 200) {
          let data = [...res.data];
          data.map(x => {
            x.color = (isEmpty(x.cr_id) ? "red" : "green");
            x.id = x.class_id;
            x.label = x.class_name + (isEmpty(x.cr_id) ? "（未提交）" : "（已提交）") + "辅导员:" + x.teacher_name;
            x.name = x.class_name + (isEmpty(x.cr_id) ? "（未提交）" : "（已提交）") + "辅导员:" + x.teacher_name;
            x.leaf = true;
          });
          resolve(data);
        } else {
          resolve([]);
        }
      }




    },
    async lookVClick(row) {
      this.lookCrNo = null;
      this.lookV = true;
      this.lookCmNo = row.cmNo;
      await this.listTreeDept();
    },

    /** 查询班会主题列表 */
    getList() {
      this.loading = true;
      listClassMettingTheme(this.queryParams).then(response => {
        this.ClassMettingThemeList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.resetForm("queryForm");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //获取附件路径
    getResUrls(url) {
      return process.env.VUE_APP_BASE_API + url;
    },
    // 表单重置
    reset() {
      this.form = {
        cmId: null,
        cmNo: null,
        cmTheme: null,
        cmTextTheme: null,
        cmTitle: null,
        cmIsupload: null,
        cmProp: null,
        attachUrls: null,
        attachResourceList: null,
        tmpResList: null,
        cmStart: null,
        cmEnd: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cmId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {};
      this.reset();
      this.open = true;
      this.title = "添加班会主题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = {};
      this.reset();
      this.tmpResList = [];
      const cmId = row.cmId || this.ids
      getClassMettingTheme(cmId).then(response => {
        this.form = response.data;
        let tmpurl = [];
        tmpurl = this.form.attachResourceList;
        this.form.attachUrls = "";
        tmpurl.forEach(item => {
          this.tmpResList.push({
            originalFileName: item.resName,
            url: item.resPath,
            name: item.resName
          });
        });
        this.open = true;
        this.title = "修改班会主题";
      });
    },
    handleOpenDetail(row) {
      this.reset();
      this.tmpResList = [];
      const cmId = row.cmId || this.ids
      getClassMettingTheme(cmId).then(response => {
        this.form = response.data;
        let tmpurl = [];
        tmpurl = this.form.attachResourceList;
        this.tmpResList = [];
        tmpurl.forEach(item => {
          this.tmpResList.push({
            originalFileName: item.resName,
            url: item.resPath,
            name: item.resName
          })
        });
        this.detailOpen = true;
        this.title = "修改班会主题";
      });
    },

    /** 提交按钮 */
    submitForm(status) {
      let attachamentFileTemp = [];
      this.tmpResList.forEach(element => {
        attachamentFileTemp.push({
          resName: element.originalFileName,
          resPath: element.url
        });
      });
      this.form.attachResourceList = attachamentFileTemp;
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.status = status;
          this.form.cmTextTheme = this.$refs.uedit.getContent();
          if (this.form.cmId != null) {
            updateClassMettingTheme(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClassMettingTheme(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cmIds = row.cmId || this.ids;
      this.$modal.confirm('是否确认删除班会主题编号为"' + cmIds + '"的数据项？').then(function () {
        return delClassMettingTheme(cmIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('runtine/ClassMettingTheme/export', {
        ...this.queryParams
      }, `ClassMettingTheme_${new Date().getTime()}.xlsx`)
    },
    getStatusName(row, column) {
      if (row.status == 0) {
        return "保存";
      }
      else if (row.status == 1) {
        return "发布";
      }
    }
  }
};
</script>
